<template>
  <div class="admin-events">
    <h1>校园活动管理</h1>

    <div class="user-info">
      <p>领导您好，欢迎使用活动管理系统</p>
      <router-link to="/admin/dashboard">返回Dashboard</router-link>
    </div>

    <!-- 发布新活动表单 -->
    <div class="create-event-section">
      <h2>发布新活动</h2>
      <form @submit.prevent="createEvent">
        <div class="form-group">
          <label for="title">活动标题:</label>
          <input type="text" id="title" v-model="eventForm.title" required />
        </div>

        <div class="form-group">
          <label for="description">活动详情:</label>
          <textarea id="description" v-model="eventForm.description" rows="4" required></textarea>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="startTime">开始时间:</label>
            <input type="datetime-local" id="startTime" v-model="eventForm.startTime" required />
          </div>

          <div class="form-group">
            <label for="endTime">结束时间:</label>
            <input type="datetime-local" id="endTime" v-model="eventForm.endTime" required />
          </div>
        </div>

        <div class="form-group">
          <label for="location">活动地点:</label>
          <input type="text" id="location" v-model="eventForm.location" required />
        </div>

        <button type="submit" class="create-btn">发布活动</button>
      </form>
    </div>

    <!-- 活动列表 -->
    <div class="events-list-section">
      <h2>已发布的活动</h2>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="events.length === 0" class="no-events">暂无活动</div>
      <div v-else class="events-list">
        <div v-for="event in events" :key="event.id" class="event-card">
          <h3>{{ event.title }}</h3>
          <p class="event-description">{{ event.description }}</p>
          <div class="event-details">
            <p><strong>时间:</strong> {{ formatDateTime(event.startTime) }} - {{ formatDateTime(event.endTime) }}</p>
            <p><strong>地点:</strong> {{ event.location }}</p>
            <p><strong>发布时间:</strong> {{ formatDate(event.createdAt) }}</p>
          </div>
          <div class="event-actions">
            <button @click="viewRegistrations(event.id)" class="view-registrations-btn">查看报名情况</button>
            <button @click="deleteEvent(event.id)" class="delete-btn">删除活动</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 报名情况模态框 -->
    <div v-if="showRegistrationModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>活动报名情况</h2>
          <span class="close" @click="closeRegistrationModal">&times;</span>
        </div>
        <div class="modal-body">
          <div v-if="registrationsLoading" class="loading">加载中...</div>
          <div v-else-if="registrations.length === 0" class="no-registrations">暂无报名</div>
          <div v-else>
            <table class="registrations-table">
              <thead>
                <tr>
                  <th>用户ID</th>
                  <th>报名时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="registration in registrations" :key="registration.id">
                  <td>{{ registration.userId }}</td>
                  <td>{{ formatDateTime(registration.registeredAt) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>

    <!-- 成功提示 -->
    <div v-if="success" class="success-message">
      {{ success }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  name: 'AdminEvents',
  setup() {
    // 活动表单
    const eventForm = ref({
      title: '',
      description: '',
      startTime: '',
      endTime: '',
      location: ''
    });

    // 活动列表
    const events = ref([]);
    const loading = ref(false);

    // 报名情况相关
    const showRegistrationModal = ref(false);
    const registrations = ref([]);
    const registrationsLoading = ref(false);

    // 状态信息
    const error = ref('');
    const success = ref('');

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const result = await response.json();
        if (result.code !== 1) {
          error.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 获取活动列表
    const loadEvents = async () => {
      loading.value = true;
      try {
        const response = await fetch('/admin/events', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          events.value = result.data || [];
        } else {
          error.value = result.msg || '获取活动列表失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      } finally {
        loading.value = false;
      }
    };

    // 发布新活动
    const createEvent = async () => {
      try {
        // 确保时间字段格式正确
        const eventData = {
          title: eventForm.value.title,
          description: eventForm.value.description,
          startTime: eventForm.value.startTime,
          endTime: eventForm.value.endTime,
          location: eventForm.value.location
        };

        const response = await fetch('/admin/events', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(eventData)
        });

        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '活动发布成功';
          // 清空表单
          eventForm.value = {
            title: '',
            description: '',
            startTime: '',
            endTime: '',
            location: ''
          };
          // 重新加载活动列表
          await loadEvents();
        } else {
          error.value = result.msg || '活动发布失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试: ' + err.message;
      }
    };

    // 删除活动
    const deleteEvent = async (eventId) => {
      if (!confirm('确定要删除这个活动吗？')) {
        return;
      }

      try {
        const response = await fetch(`/admin/events/${eventId}`, {
          method: 'DELETE',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '活动删除成功';
          // 重新加载活动列表
          await loadEvents();
        } else {
          error.value = result.msg || '活动删除失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 查看报名情况
    const viewRegistrations = async (eventId) => {
      registrationsLoading.value = true;
      showRegistrationModal.value = true;
      registrations.value = [];

      try {
        const response = await fetch(`/admin/events/${eventId}/registrations`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          registrations.value = result.data || [];
        } else {
          error.value = result.msg || '获取报名列表失败';
        }

      } finally {
        registrationsLoading.value = false;
      }
    };

    // 关闭报名情况模态框
    const closeRegistrationModal = () => {
      showRegistrationModal.value = false;
    };

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '';
      return new Date(dateTime).toLocaleString('zh-CN');
    };

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '';
      return new Date(date).toLocaleDateString('zh-CN');
    };

    // 初始化
    onMounted(async () => {
      await loadUserProfile();
      await loadEvents();
    });

    return {
      eventForm,
      events,
      loading,
      showRegistrationModal,
      registrations,
      registrationsLoading,
      error,
      success,
      createEvent,
      deleteEvent,
      viewRegistrations,
      closeRegistrationModal,
      formatDateTime,
      formatDate
    };
  }
};
</script>

<style scoped>
.admin-events {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.create-event-section, .events-list-section {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.create-event-section h2, .events-list-section h2 {
  margin-top: 0;
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #555;
}

.form-group input, .form-group textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;
}

.create-btn, .view-registrations-btn, .delete-btn {
  background-color: #2196F3;
  color: white;
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.3s;
}

.delete-btn {
  background-color: #f44336;
}

.create-btn:hover, .view-registrations-btn:hover {
  background-color: #0b7dda;
}

.delete-btn:hover {
  background-color: #d32f2f;
}

.event-card {
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.event-card h3 {
  margin-top: 0;
  color: #333;
}

.event-description {
  color: #666;
  margin-bottom: 15px;
}

.event-details p {
  margin: 5px 0;
}

.event-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.loading, .no-events, .no-registrations {
  text-align: center;
  padding: 20px;
  color: #666;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

/* 模态框样式 */
.modal {
  display: block;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: #fff;
  margin: 10% auto;
  padding: 0;
  border: 1px solid #888;
  width: 80%;
  max-width: 600px;
  border-radius: 5px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.modal-header {
  padding: 15px 20px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
}

.close {
  color: #aaa;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}

.close:hover {
  color: #000;
}

.modal-body {
  padding: 20px;
}

.registrations-table {
  width: 100%;
  border-collapse: collapse;
}

.registrations-table th,
.registrations-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.registrations-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}
</style>